package com.zlp.partice.io.threadpool;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author: zhulaiping
 * @time: 2022/8/5 15:59
 */
public class TCPServer2 {

    public static void main(String[] args) {
        try {
            ServerSocket serverSocket = new ServerSocket(8899);
            //初始化线程池对象
            SocketHandler handler = new SocketHandler(4, 10);
            while (true){
                Socket accept = serverSocket.accept();
                Runnable task = new ServerRunnable(accept);
                handler.execute(task);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    static class SocketHandler{

        private ExecutorService executorService;

        public SocketHandler(int maxThreads,int queueSize){
            executorService =
                    new ThreadPoolExecutor(3,maxThreads,120, TimeUnit.SECONDS,new ArrayBlockingQueue<>(queueSize));
        }

        public void execute(Runnable task){
            executorService.execute(task);
        }
    }

    static class ServerRunnable implements Runnable{

        private Socket socket;

        public ServerRunnable(Socket socket){
            this.socket = socket;
        }

        @Override
        public void run() {
            try {
                BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                String msg;
                while ((msg = br.readLine())!=null){
                    System.out.println(Thread.currentThread().getName()+":"+msg);
                }
            }catch (Exception e){

            }
        }
    }

}

